/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:13:08
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-06-23 17:47:15
 */
import './windowFun';
import isEqual from 'lodash/isEqual';

export const listRoute = [
  'inbox',
  'sent',
  'draft',
  'deleted',
  'doing',
  'star',
  'inner',
  'folder',
  'tag',
];

export const listParams = {
  inbox: { folderid: 0 },
  sent: { folderid: -1 },
  draft: { folderid: -2 },
  deleted: { folderid: -3 },
  doing: { waitdeal: 1 },
  star: { star: 1 },
  inner: { isInternal: 1 },
  folder: { folderid: '' },
  tag: { labelid: '' },
};

export const nameLowerCase = name => name.charAt(0).toLowerCase() + name.slice(1).toLowerCase();
export const nameUpperCase = name => name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();

export function checkKeyinTab(datas, key) {
  const filterDatas = datas.filter(data => data.tabKey === key);
  return filterDatas.length === 1 ? filterDatas[0].tabKey : null;
}

export function checkTypeinTab(datas, type) {
  const filterDatas = datas.filter(data => data.type === type);
  return filterDatas.length > 0 ? filterDatas[0].type : null;
}

export function checkChangeinTab(datas, key, query) {
  const filterDatas = datas.filter(({ tabKey, query: _query }) =>
    tabKey === key && !isEqual(query, _query));
  return filterDatas.length === 1 ? filterDatas[0] : null;
}

const n = {
  Rr: 'icon-email-read', // 已读
  Ru: 'icon-email-Unread', // 未读
  draw: 'icon-email-withdraw', // 撤回
  Rp: 'icon-email-Replies', // 已回复
  Fw: 'icon-email-Forward', // 已转发
  Rf: 'icon-email-Forward-and-reply', // 已转发且已回复
  edit: 'icon-email-error', // 发送失败
  timingdate: 'icon-email-timing', // 定时发送
  file: 'icon-email-Enclosure', // 附件
  fav: 'icon-email-Collection', // 收藏
  agency: 'icon-email-Agency', // 待办
  invoice_right: 'icon-coms02-Finance-right', // 发票识别成功
  invoice_wrong: 'icon-coms02-Finance-Wrong', // 发票识别失败
};

const o = {};
Object.keys(n).forEach((k) => {
 o[k] = `${n[k]}-o`; 
});

const flagCls = { n, o };

export const getFlagCls = (key, type = 'n') => flagCls[type][key];

// '1' 今天
// '2' 明天
// '3' 后天
// '4' 下周（7天后）
// '5' 下个月（30天后）
// '6' 自定义
const vToDay = ['null', 0, 1, 2, 7, 30];
const toLocaleDateString = d => `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;

export const chanageValueToDate = v => (vToDay[v] !== undefined
  ? toLocaleDateString(new Date(new Date().getTime() + 1000 * 3600 * 24 * vToDay[v]))
    .replace(/\//g, () => '-')
  : '');

export const chanageDateToValue = (date) => {
  const v = String(vToDay.indexOf(
    Math.ceil(
      (new Date(date.replace(/\-/g, () => '/')).getTime()
        - new Date(toLocaleDateString(new Date())).getTime()
      ) / (1000 * 3600 * 24),
    ),
  ));
  return v === '-1' ? '6' : v;
};

export const getFileTypeCls = exName => (
  /^\.?(txt|doc|docx|wps|md)$/ig.test(exName)
  ? 'icon-coms-word2'
  : /^\.?(rar|zip|gz|z|7z)$/ig.test(exName)
  ? 'icon-coms-rar2'
  : /^\.?(ppt|pptx)$/ig.test(exName)
  ? 'icon-coms-ppt2'
  : /^\.?(png|jpg|jpeg|gif|bmp)$/ig.test(exName)
  ? 'icon-coms-pic2'
  : /^\.?(pdf)$/ig.test(exName)
  ? 'icon-coms-pdf2'
  : /^\.?(html|htm|jsp|php|js|css)$/ig.test(exName)
  ? 'icon-coms-html2'
  : /^\.?(xls|xlsx)$/ig.test(exName)
  ? 'icon-coms-excel2'
  : 'icon-coms-currency2'
);

export const noRepeat = (datas = [], key = 'id', type = 'type') => {
  let keys = [],
userKeys = [];
  datas.forEach((d) => {
    let userids = d.users ? d.users.map(v => `${v[key]}_${v[type]}`) : []; // 判断是否为公共组
    keys.push(`${d[key]}_${d[type]}`, ...userids);
    userKeys.push(...userids);
  });
  keys = [...new Set(keys)];
  userKeys = [...new Set(userKeys)];
  const newDatas = datas.filter((d) => {
    if (keys.indexOf(`${d[key]}_${d[type]}`) < 0 || userKeys.indexOf(`${d[key]}_${d[type]}`) >= 0) return false;
    keys = keys.filter(k => k !== `${d[key]}_${d[type]}`);
    return true;
  });
  return newDatas;
};

export const isSelectedAll = (datas = []) => {
  const newDatas = datas.filter(d => d.type === 'all');
  return newDatas.length === 1;
};

export const emailValidate = (v) => {
  let emailReg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/g;
  if (emailReg.test(v)) {
    let emailArr = v.match(emailReg);
    let result = emailReg.test(v) && emailArr.length === 1;
    return !result;
  }
    return !emailReg.test(v);
};

export const transfStr = (...arg) => {
  let name = arg[0] || '',
list = arg[2] || [],
type = arg[3] || '';
  let str = '';
  const mirror = {
    37: 'doc',
    prjtsk: 'prjtsk',
    18: 'crm',
    152: 'workflow',
    8: 'project',
    workplan: 'workplan',
    blogTemplate: 'blogTemplate',
  };
  const url = {
    doc: '/spa/document/index.jsp?router=1&id=',
    project: '/spa/prj/index.html#/main/prj/projectCard?prjid=',
    prjtsk: '/proj/process/ViewTask.jsp?taskrecordid=',
    crm: '/spa/crm/static/index.html#/main/crm/customerView?customerId=',
    workflow: '/workflow/request/ViewRequestForwardSPA.jsp?requestid=',
    workplan: '/spa/workplan/static/index.html#/main/wp/workPlanCreateSingle?workPlanId=',
  };
  list.forEach((item) => {
    if (name === 'Upload' && type === 'image') {
      // str += '<img class="formImgPlay" src="' + item.filelink + '" data-imgsrc="' + (item.loadlink || item.filelink) + '" />';
      str += `&nbsp;<img src="${item.imgSrc}"/>&nbsp;`;
    }
   /*  if (name === 'Upload' && type === 'file') {
      str += (item.filelink + '<br>');
    } */
    let location = `'${url[mirror[type]]}${item.id}'`;
    mirror[type] === 'doc' && (location = `'${url[mirror[type]]}${item.id}#/main/document/detail'`);
    if (name === 'Browser') {
      str += `<a linkid='${item.id}' linkType='${type}' href=${location}`
      + "target='_blank' ondblclick='return false;'  unselectable='off' contenteditable='false'"
      + "style='cursor:pointer;text-decoration:underline !important;margin-right:8px'"
      + `>${item.name || item.showname}</a>&nbsp;`;
    }
  });
  return str;
};

/* 验证form 表单 */
export const ValidateForm = (form, callback) => {
  form.validateForm().then((f) => {
    if (f.isValid) {
      if (callback) callback();
    } else {
      f.showErrors();
    }
  });
};
